# -*- coding: utf-8 -*-

from onlinebrary.lib.base import *

import logging
from pylons import session

log = logging.getLogger(__name__)

class MainController(BaseController):

    def __init__(self):
        pass

    def index(self):
       
        if session.has_key('urls'):
            c.urls = session['urls']
        else:
            c.urls = ""
        return render('/main.mako')

    def __sanitize(self, query):
        return query.strip()

    def clear(self):
        if session.has_key('urls'):
            session['urls'] = ""
            session.save()
        return ""

    def querying(self):
    
        log.debug('Querying')
    
        if not session.has_key('urls'):
            session['urls'] = ""
            
        try:
            if request.params.has_key('query'):
                query = request.params['query']
                query = self.__sanitize(query)

                if len(query) < 5:
                    log.warn('Small query size: query = %s, len = %d', query, len(query))
                    return g.viewer.parse_error('Запрос должен быть больше 4 символов') + session['urls']
            
                result = g.processor.process(query)
            
                # FIXME: we need to save not rendered template but naked data            
                session['urls'] = str(result) + session['urls']
                session.save()
                return session['urls']
        except Exception, e:
            log.error(e)
            return str(g.viewer.parse_error(g.default_error_msg)) + session['urls']
            
            
            
            
            
                
